<?php

namespace app\product\logic;
use app\common\library\Excel;
use app\common\library\Upload;
use app\data\util\MqQueueName;
use app\systems\logic\OperateSystemLogic;
use app\product\validate\ProductEdit;
use app\product\validate\ProductAdd;
use app\product\validate\ProductSku;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;

class ProductLogic extends BasicLogic
{

    /**
     * @desc  产品列表
     * @date  2024/4/20
     */
    public function getProductList($params=[]){
        $limit           = getIsset($params,'limit',10);
        $spu             = getIsset($params,'spu');
        $product_attr_id = getIsset($params,'product_attr_id');
        $published_time  = getIsset($params,'published_time');
        $purchase_type   = getIsset($params,'purchase_type');
        $develop_type    = getIsset($params,'develop_type');
        $supply_id       = getIsset($params,'supply_id');
        $product_status  = getIsset($params,'product_status');
        $product_tag     = getIsset($params,'product_tag');

        $spu_3days       = $params['spu_3days'] ??'';
        $spu_7days       = $params['spu_7days'] ??'';
        $spu_30days      = $params['spu_30days']??'';
        $where = [];
        $order = [];
        if($spu){
            $where[] = ['p.spu', 'like', '%' . $spu . '%'];
        }

        if (!empty($published_time)) {
            $where[]  = ['p.published_time', '>=', date('Y-m-d H:i:s',strtotime($published_time[0]))];
            $where[]  = ['p.published_time', '<=', date('Y-m-d H:i:s',strtotime($published_time[1]) + 3600*24-1)];
        }

        if($purchase_type){
            $where[] = ['p.purchase_type', '=',$purchase_type];
        }

        if($develop_type){
            $where[] = ['p.develop_type', '=',$develop_type];
        }

        if($product_status){
            $where[] = ['p.product_status', '=',$product_status];
        }

        if($product_attr_id){
            $where[] = ['p.product_attr_type', '=',$product_attr_id];
        }

        if($supply_id){
            $where[] = ['p.source_link','=' ,$supply_id];
        }


        if($spu_3days){
            $order['p.spu_3days']  = $spu_3days;
        }
        if($spu_7days){
            $order['p.spu_7days']  = $spu_7days;
        }
        if($spu_30days){
            $order['p.spu_30days'] = $spu_30days;
        }

        if(!$order){
            $order['p.update_time'] = 'desc';
        }

        if($product_tag=='1'){
            $where[] = ['p.product_new', '=',1];
        }

        if($product_tag=='2'){
            $where[] = ['p.product_sales', '=',2];
        }

        $field = 'p.id,p.spu,p.product_type_1,p.product_type_2,p.product_name,p.size_variant,
                  p.color_variant,p.product_size_images,p.size_type,
                  p.purchase_cost,p.month_purchase_cost,p.source_link,p.develop_type,
                  p.max_weight,p.min_weight,p.estimate_shipping_fee,p.spu_3days,p.spu_7days,p.product_sales,
                  p.published_time,p.spu_30days,p.develper,p.product_new,p.product_sales,p.product_status,p.GrowthRate,
                  p.remarks,p.product_images,p.source_link,p.remarks,p.fabric_content,append.is_steel,
                  append.is_shoulder,append.adjust_shoulder,append.buckling_method,
                  append.cup_type,append.pant_shape,p.product_attr_type,p.purchase_type,
                  append.shap_sleeve_type,append.shapewear_number,append.swim_closed_form,
                  append.panties_type,append.top_sleeve_type';


        $res   = Db::name('product')
            ->alias('p')
            ->leftJoin('product_append append', 'p.spu = append.spu')
            ->field($field)
            ->where($where)
            ->group('p.spu')
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];

        //批量获取产品大类;
        $product_types      = array_column($list,'product_type_1');
        $product_types_info = Db::name('product_level')->field('type_id,type_name')->whereIn('type_id',$product_types)->select();
        $product_types_info = objectToArray($product_types_info);
        $product_types_map  = array_column($product_types_info,null,'type_id');

        $product_attr_type = Db::name('product_attr_level')->field('type_id,type_name')->where(['parent_id'=>0])->select()->toArray();
        $product_attr_type_map = array_column($product_attr_type,null,'type_id');
        foreach($list as $k=>$v){
            $product_type                        = $product_types_map[$v['product_type_1']]??[];
            $product_images                      = $v['product_images'] ? json_decode($v['product_images'],true):'';
            $image_product                       = $product_images ? current($product_images) : '';
            $product_size_images                 = $v['product_size_images'] ? json_decode($v['product_size_images'],true):'';
            $image_size                          = $product_size_images ? current($product_size_images) : '';
            $list[$k]['product_type_1']          = $product_type['type_name']??'';
            $links                               = self::get_links($v['source_link']);
            $list[$k]['supply_links']            = $links;
            $list[$k]['product_images']          = $image_product;
            $list[$k]['product_size_images']     = $image_size;
            $list[$k]['product_images_arr']      = $product_images;
            $list[$k]['product_tag']             = self::get_product_tag($v);
            $list[$k]['product_size_images_arr'] = $product_size_images;
            $product_attr_type_value             = $product_attr_type_map[$v['product_attr_type']]??[];
            $list[$k]['product_attr_type_value'] = $product_attr_type_value['type_name']??'';
            if(!$v['min_weight']){
                $v['min_weight'] = '0.00';
            }
            if(!$v['max_weight']){
                $v['max_weight'] = '0.00';
            }
            $list[$k]['min_weight']              = getRes($v['min_weight']);
            $list[$k]['max_weight']              = getRes($v['max_weight']);
            $average_weight                      = ($v['min_weight']+$v['max_weight'])/2;
            $list[$k]['average_weight']          = getRes($average_weight);
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc    获取详情
     * @date    2024/7/17
     * @author  luckyXiong
     */
    public function get_links($links=''){
        if(empty($links))  return [];
        $links   = explode(',',$links);
        $where   = [];
        $where[] = ['i.id','in',$links];
        $field   = "s.supply_name,i.supply_link,i.spu,i.remark";
        $res     = Db::name('supply')
            ->alias('s')
            ->leftJoin('supply_info i', 's.id = i.supply_id')
            ->field($field)
            ->where($where)
            ->select();
        $res = objectToArray($res);
        if($res){
            foreach($res as $k=>$v){
                if($v['supply_name'] && $v['spu']){
                    if($v['remark']){
                        $res[$k]['supply_name'] = $v['spu'].'-'.$v['supply_name'].'-'.$v['remark'];
                    }else{
                        $res[$k]['supply_name'] = $v['spu'].'-'.$v['supply_name'];
                    }
                }
            }
        }
        return  objectToArray($res);
    }



    /**
     * @desc    获取详情
     * @date    2024/7/03
     * @author  luckyXiong
     */
    public function getInfo($params=[]){
        $id          = getIsset($params,'id');
        if(!$id){
            return  $this->jsonMessage(201,false,'ID不能为空!',null);
        }

        //获取产品详情数据;
        $field = 'p.id,p.spu,p.product_type_1,p.product_type_2,p.product_type_3,p.product_name,p.size_variant,p.color_variant,p.product_size_images,p.size_type,
                  p.purchase_cost,p.month_purchase_cost,p.sub_purchase_cost,p.source_link,p.max_weight,p.min_weight,p.estimate_shipping_fee,
                  p.published_time,p.develper,p.product_status,p.develop_type,p.remarks,p.product_images,p.source_link,p.remarks,p.fabric_content,append.is_steel,append.is_shoulder,append.adjust_shoulder,append.buckling_method,
                  append.cup_type,append.pant_shape,p.develper,p.month_purchase_cost,p.invent_numbers,p.purchase_type,append.shap_sleeve_type,append.shapewear_number,append.swim_closed_form,append.panties_type,append.top_sleeve_type'
        ;
        $where = [];
        $where[] = ['p.id','=',$id];
        $info   = Db::name('product')
            ->alias('p')
            ->leftJoin('product_append append', 'p.spu = append.spu')
            ->field($field)
            ->where($where)
            ->find();

        //获取子集信息
        $append = Db::name('product_append')->where('product_id',$id)->find();
        $info['attr_values']     = isset($append['product_attr_types'])&&$append['product_attr_types'] ? json_decode($append['product_attr_types']) : '';
        $info['supply_links']    = $info['source_link'];
        $info['supplyList']      = [$info['source_link']];
        $info['supply_links_ids']= $info['source_link'];
        return  $this->jsonMessage(200,true,'获取成功',$info);
    }


    private function get_product_tag($info){
            $arr           = [];
            $product_tag   = Config('Logisticskey.product_tag');
            $product_new   = $info['product_new'];
            $product_sales = $info['product_sales'];
            $value         = [];
           if($info['product_new']){
                $value[]       = $info['product_new'];
            }

            if($info['product_sales']){
                $value[]       = $info['product_sales'];
            }


            if(count($value)==1){
                if($product_new=='1'){
                    $arr[] = $product_tag[1];
                }elseif($product_sales=='2'){
                    $arr[] = $product_tag[2];
                }
            }

            if(count($value)==2){
                $arr[] = $product_tag[1];
                $arr[] = $product_tag[2];
             }
            if($arr){
                 $arr = implode(',',$arr);
            }
            return  $arr?:'';
    }



    /**
     * @desc    product_tag
     * @date    2024/12/03
     * @author  luckyXiong
     */
    public function getproductTag(){
        $size_type   = Config('Logisticskey.product_tag');
        $info        = getLevel($size_type);
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }



    /**
     * @desc    新增产品接口
     * @date    2024-07-03
     * @author  luckyXiong
     */
    public function add_product($params=[]){
        //验证器参数验证
        $validate = new ProductAdd();
        $res = $validate->check($params);
        if(!$res) return $this->jsonMessage(201, false, $validate->getError(), null);
        $supply_ids = $params['supplyList']??'';
        $spu         = trim($params['spu']) ?? '';
        //查看spu数据是否存在;
        $exist_product = Db::name('product')->where('spu',$spu)->find();
        if($exist_product){
            return  $this->jsonMessage(201,false,'产品数据已存在!',null);
        }

        $attr_values    = $params['attr_values']??[];

        $attr_type    = '';
        if($attr_values){
            $current = current($attr_values);
            if(isset($current['parent_id']) && $current['parent_id']==0){
                $attr_type = $current['children_id']??'';
            }elseif(isset($current['parent_id']) && $current['parent_id']!=0){
                $new_parent_id =  Db::name('product_attr_level')->where(['type_id'=>$current['parent_id']])->value('parent_id');
                $attr_type     =  $new_parent_id??'';
            }
        }

        $published_time  =  isset($params['published_time']) &&$params['published_time'] ? $params['published_time'] : date("Y-m-d H:i:s", time());

        $invent_numbers  =   isset($params['invent_numbers']) &&$params['invent_numbers'] ? $params['invent_numbers'] :0 ;

        //主表数据写入
        $product_insert = [
            'spu'                      => trim($params['spu']) ?? '',
            'product_type_1'           => trim($params['product_type_1']) ?? '',
            'product_type_2'           => trim($params['product_type_2']) ?? '',
            'product_type_3'           => trim($params['product_type_3']) ?? '',
            'product_attr_type'        => $attr_type,
            'product_images'           => isset($params['product_images']) ? json_encode($params['product_images']) : '',
            'product_name'             => isset($params['product_name']) ? trim($params['product_name'])  : '',
            'size_variant'             => isset($params['size_variant'])  ? trim($params['size_variant']) : '',
            'color_variant'            => isset($params['color_variant']) ? trim($params['color_variant']) : '',
            'product_size_images'      => $params['product_size_images'] ? json_encode($params['product_size_images']) : '',
            'size_type'                => isset($params['size_type']) ? trim($params['size_type']) : '',
            'purchase_cost'            => isset($params['purchase_cost']) ? trim($params['purchase_cost']) : '',
            'sub_purchase_cost'        => isset($params['sub_purchase_cost']) ? trim($params['sub_purchase_cost']) : '',
            'month_purchase_cost'      => isset($params['month_purchase_cost']) ? trim($params['month_purchase_cost']) : '',
            'purchase_type'            => isset($params['purchase_type']) ? trim($params['purchase_type']) : '',
            'develop_type'             => isset($params['develop_type']) ? trim($params['develop_type']) : '1',
            'max_weight'               => isset($params['max_weight']) ? trim($params['max_weight']) : '',
            'min_weight'               => isset($params['min_weight']) ? trim($params['min_weight']) : '',
            'estimate_shipping_fee'    => isset($params['estimate_shipping_fee']) ? trim($params['estimate_shipping_fee']) : '',
            'published_time'           => $published_time,
            'invent_numbers'           => $invent_numbers,
            'remarks'                  => isset($params['remarks']) ? trim($params['remarks']) :'',
            'develper'                 => isset($params['develper']) ? trim($params['develper']) :'',
            'fabric_content'           => isset($params['fabric_content']) ? trim($params['fabric_content']) : '',
            'product_status'           => $params['product_status'] ?? '0',
            'update_time'              => date("Y-m-d H:i:s", time()),
            'created_time'             => date("Y-m-d H:i:s", time()),
        ];

        //附属表信息获取;
        $product_append = self::get_append_info($params);
        // update 2024-09-24  将新增spu成本价格同步到 qu_ordercheck_spucost 表;
        self::updateSpuPrice($product_insert);
        try {
            Db::startTrans(); // 开启事务
            $product_insert['source_link'] = $supply_ids ? implode(',',$supply_ids) : '';
            $product_id = Db::name('product')->insertGetId($product_insert);
            $product_append['product_id'] = $product_id;
            Db::name('product_append')->insert($product_append);
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '新增成功', ''));
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }
    }


    /**
     * @desc    编辑产品接口
     * @date    2024-07-05
     * @author  luckyXiong
     */
    public function edit_product($params=[]){
        //验证器参数验证
        $validate = new ProductEdit();
        $res = $validate->check($params);
        if(!$res) return $this->jsonMessage(201, false, $validate->getError(), null);
        $spu         = trim($params['spu']) ?? '';
        $id          = trim($params['id']) ?? '';

        //获取append,supply表,对应老spu的ID
        $old_spu_info =  Db::name('product')->where(['id'=>$id])->field('id,source_link')->find();
        $append_id    =  Db::name('product_append')->where(['product_id'=>$old_spu_info['id']])->value('id');
        //查看原始产品是否存在source_link
        $source_link  = $params['supplyList']??'';
        $attr_values  = $params['attr_values']??[];
        $attr_type    = '';
        if($attr_values){
            $current = current($attr_values);
            if(isset($current['parent_id']) && $current['parent_id']==0){
                $attr_type = $current['children_id']??'';
            }elseif(isset($current['parent_id']) && $current['parent_id']!=0){
                $new_parent_id =  Db::name('product_attr_level')->where(['type_id'=>$current['parent_id']])->value('parent_id');
                $attr_type     =  $new_parent_id??'';
            }
        }

        $invent_numbers  =  isset($params['invent_numbers']) &&$params['invent_numbers'] ? $params['invent_numbers'] :0 ;

        $product_images = '';
        $product_size_images = '';
        if(isset($params['product_images'])&&$params['product_images']){
            $params['product_images'] = array_filter($params['product_images']);
            $product_images = json_encode(array_values($params['product_images']));
        }
        if(isset($params['product_size_images'])&&$params['product_size_images']){
            $params['product_size_images'] = array_filter($params['product_size_images']);
            $product_size_images = json_encode(array_values($params['product_size_images']));
         }
        //主表数据写入
        $product_update = [
            'spu'                      => $spu,
            'product_type_1'           => trim($params['product_type_1']) ?? '',
            'product_type_2'           => trim($params['product_type_2']) ?? '',
            'product_type_3'           => trim($params['product_type_3']) ?? '',
            'product_attr_type'        => $attr_type,
            'product_images'           => $product_images,
            'product_name'             => isset($params['product_name']) ? trim($params['product_name']) : '',
            'size_variant'             => isset($params['size_variant']) ? trim($params['size_variant']) : '',
            'color_variant'            => isset($params['color_variant']) ? trim($params['color_variant']) : '',
            'product_size_images'      => $product_size_images,
            'size_type'                => isset($params['size_type']) ? trim($params['size_type']) : '',
            'purchase_cost'            => isset($params['purchase_cost']) ? trim($params['purchase_cost']) : '',
            'sub_purchase_cost'        => isset($params['sub_purchase_cost']) ? trim($params['sub_purchase_cost']) : '',
            'month_purchase_cost'      => isset($params['month_purchase_cost']) ? trim($params['month_purchase_cost']) : '',
            'purchase_type'            => isset($params['purchase_type']) ? trim($params['purchase_type']) : '',
            'develop_type'             => isset($params['develop_type']) ? trim($params['develop_type']) : '1',
            'max_weight'               => isset($params['max_weight']) ? trim($params['max_weight']) : '',
            'min_weight'               => isset($params['min_weight']) ? trim($params['min_weight']) : '',
            'estimate_shipping_fee'    => isset($params['estimate_shipping_fee']) ? trim($params['estimate_shipping_fee']) : '',
            'invent_numbers'           => $invent_numbers,
            'remarks'                  => isset($params['remark']) ? trim($params['remark']) :'',
            'develper'                 => isset($params['develper']) ? trim($params['develper']) :'',
            'fabric_content'           => isset($params['fabric_content']) ? trim($params['fabric_content']) : '',
            'product_status'           => $params['product_status'] ?? '0',
            'update_time'              => date("Y-m-d H:i:s", time()),
            'created_time'             => date("Y-m-d H:i:s", time()),
           ];
            $published_time  =  isset($params['published_time']) &&$params['published_time'] ? $params['published_time'] : null;

            if($published_time){
                $product_update['published_time'] = $published_time;
            }

            //附属表信息获取;
            $product_append_update = self::get_append_info($params);

            $product_update['source_link'] = $source_link ? implode(',',$source_link) : '';
            // update 2024-09-24 将新增spu成本价格同步到 qu_ordercheck_spucost 表;
            self::updateSpuPrice($product_update);
        try {
            Db::startTrans(); // 开启事务
            //记录日志结束
            self::add_log($params,$product_update,1);
            Db::name('product')->where('id',$id)->update($product_update);
            Db::name('product_append')->where('id',$append_id)->update($product_append_update);
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '编辑成功', ''));
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }

    }


    /**
     * @desc    维护供应商和spu关系表
     * @date    2024-10-22
     * @author  luckyXiong
     */
    public function add_spu($info,$spu){
        foreach($info as $v){
              $exist_spu = Db::name('supply_info')->where(['spu'=>$spu,'supply_id'=>$v])->find();

              if(!$exist_spu){
                  Db::name('supply_info')->insert([
                      'supply_id'         =>$v,
                      'spu'               =>$spu,
                      'supply_link'       =>'供应链开发',
                      'created_time'      =>date("Y-m-d H:i:s", time()),
                  ]);
              }
        }
    }


    private function add_log($params=[],$product_update,$type=1){
           $field = 'id,spu,product_type_1,product_type_2,product_type_3,product_name,size_variant,color_variant,product_size_images,size_type,
                  purchase_cost,month_purchase_cost,source_link,max_weight,min_weight,estimate_shipping_fee,
                  published_time,develper,product_status,develop_type,remarks,product_images,source_link,remarks,fabric_content,
                  develper,month_purchase_cost,invent_numbers,purchase_type';
           $old_info = Db::name('product')->field($field)->where(['id'=>$params['id']])->find();
           $data = [
               'adminId'          =>$params['adminId'],
               'source_id'        =>$params['id'],
               'title'            => ($type == '1') ? '编辑产品' : (($type == '2') ? '产品删除' : '产品新增'),
               'operate_type'     =>$type,
               'content_before'   =>$old_info ? json_encode($old_info):'',
               'content_after'    =>$product_update ? json_encode($product_update):'',
           ];
           (new OperateSystemLogic)->add_log($data);
    }



    /**
     * @desc    维护供应商和spu关系表
     * @date    2024-10-22
     * @author  luckyXiong
     */
    public function change_spu($info,$source_link,$spu){
        $info        = explode(',',$info);
        foreach($info as $v){
               if(!in_array($v,$source_link)){
                   //删除supply与spu绑定关系;
                   Db::name('supply_info')->where(['spu'=>$spu,'supply_id'=>$v])->delete();
               }
        }
    }




    /**
     * @desc    产品删除接口
     * @date    2024-08-22
     * @author  luckyXiong
     */
    public function del_product($params=[]){
           $id   = $params['id']??'';
           if(!$id) {
               return json(DefaultResponse(201, false, 'ID不能为空!', ''));
           }
           $exist_append = Db::name('product_append')->where('product_id',$id)->find();
           Db::name('product')->where('id',$id)->delete();
           //记录日志
           self::add_log($params,[],2);
           if($exist_append){
               Db::name('product_append')->where('product_id',$id)->delete();
           }
           return json(DefaultResponse(200, true, '操作成功!', ''));
    }


    /**
     * @desc    产品同步成本价格
     * @date    2024-09-23
     * @author  luckyXiong
     */
    public function updateSpuPrice($product_update=[]){
           if(!$product_update['purchase_cost'])  return  '';
           //查看spu成本表是否有数据 qu_ordercheck_spucost
           $exist_info = Db::name('ordercheck_spucost')->where(['spu'=>$product_update['spu']])->find();
           $currentMonth = date('m');
           $currentYear  = date('Y');
           $update_info= [
               'spu'     =>$product_update['spu'],
               'material'=>$product_update['purchase_cost'],
               'date'    =>$currentYear.'-'.$currentMonth,
               'timedate'=>time()
           ];
           if($product_update['product_images']){
               $product_images  = current(json_decode($product_update['product_images']));
               $update_info['product_images'] = $product_images;
           }
           if(empty($exist_info)){
               Db::name('ordercheck_spucost')->insert($update_info);
           }
    }


    /**
     * @desc    组合sku接口
     * @date    2024-07-05
     * @author  luckyXiong
     */
    public function add_seller_sku($params=[]){
        //验证器参数验证
        $validate = new ProductSku();
        $res = $validate->check($params);
        if(!$res) return $this->jsonMessage(201, false, $validate->getError(), null);
        $product_id   = $params['product_id'];
        $product_name = $params['product_name'];
        $spu          = $params['spu'];
        $variant_arr  = $params['variant_arr']??[];

        $insert_info= [];
        foreach($variant_arr as $k=>$v){
            $image_info                      = $v['image_info']??[];
            $insert_info[$k]['spu']          = $spu;
            $insert_info[$k]['product_name'] = $product_name;
            $insert_info[$k]['product_id']   = $product_id;
            $insert_info[$k]['seller_sku']   = $v['seller_sku']??'';
            $insert_info[$k]['platform_sku'] = $v['platform_sku']??'';
            $insert_info[$k]['seller_sku_cn']= $v['seller_sku_cn']??'';
            $insert_info[$k]['seller_sku_en']= $v['seller_sku_en']??'';
            $insert_info[$k]['seller_sku_url']= $v['seller_sku_url']??'';
            $insert_info[$k]['image_info']    = $image_info ? json_encode($image_info) : '';
        }
        Db::name('product_seller_sku')->insertAll($insert_info);
        return json(DefaultResponse(200, true, '添加成功', null));
    }


    /**
     * @desc    获取sku的子集列表
     * @date    2024-07-10
     * @author  luckyXiong
     */
    public function getSellerSkuList($params=[]){
           $product_id  = $params['product_id']??'';
           $limit       = $params['lmit']??10;
           if(!$product_id) return  $this->jsonMessage(201,false,'产品ID不能为空!',null);
           $field = 'id,product_id,spu,product_name,seller_sku,platform_sku,seller_sku_cn,seller_sku_en,seller_sku_url,image_info';
           $res  = Db::name('product_seller_sku')->field($field)
                   ->where('product_id',$product_id)
                   ->paginate($limit);
          $list = $res->items()?:[];
          foreach($list as $k=>$v){
              $list[$k]['image_info'] = $v['image_info']  ?: Config('Logisticskey.product_image_default');
          }
          $data = [
              'list' =>$list,
              'total'=>$res->total()
          ];
          return json(DefaultResponse(200, true, '获取成功', $data));
    }


    /**
     * @desc    编辑sku的子集列表
     * @date    2024-07-10
     * @author  luckyXiong
     */
    public function editSellerSku($params=[]){
           $id = $params['id']??'';
           if(!$id)  return  $this->jsonMessage(201,false,'ID不能为空!',null);
           $seller_sku      = getIsset($params,'seller_sku');
           $platform_sku    = getIsset($params,'platform_sku');
           $seller_sku_cn   = getIsset($params,'seller_sku_cn');
           $seller_sku_en   = getIsset($params,'seller_sku_en');
           $seller_sku_url  = getIsset($params,'seller_sku_url');
           $image_info      = getIsset($params,'image_info');
           if($image_info){
               $image_info = end($image_info);
           }
           $update_arr = [
               'seller_sku'     =>$seller_sku,
               'platform_sku'   =>$platform_sku,
               'seller_sku_cn'  =>$seller_sku_cn,
               'seller_sku_en'  =>$seller_sku_en,
               'seller_sku_url' =>$seller_sku_url,
               'image_info'     =>$image_info ?  : '',
           ];
           Db::name('product_seller_sku')->where('id',$id)->update($update_arr);
        return json(DefaultResponse(200, true, '编辑成功', null));
    }

    /**
     * @desc     sku添加颜色处理
     * @author   luckyXiong
     * @date     2024-07-11
     */
    public function addColor($params=[]){
        $color_name = $params['color_name']??'';
        $exist_name = Db::name('product_options_dic')->where(['attr_type'=>1,'attr_value'=>$color_name])->find();
        if(!$exist_name){
            $new_id = Db::name('product_options_dic')->insertGetId(
                [
                    'attr_type'=>1,
                    'attr_value'   =>$color_name
                ]
            );
            $data = [
                'id'        =>$new_id,
                'color_name'=>$color_name,
            ];
        }else{
            $data = [
                'id'        =>$exist_name['id'],
                'color_name'=>$exist_name['attr_value'],
            ];
        }
        return json(DefaultResponse(200, true, '操作成功', $data));
    }



    /**
     * @desc     sku删除颜色处理
     * @author   luckyXiong
     * @date     2024-07-11
     */
    public function deleteColor($params=[]){
        $color_id = $params['color_id']??'';
        Db::name('product_options_dic')->where(['id'=>$color_id])->delete();
        return json(DefaultResponse(200, true, '操作成功', null));
    }





    /**
     * @desc     获取产品属性基础分类
     * @author   luckyXiong
     * @date     2024-07-11
     */
    public function getAttrList(){
        $product_attr_type = Db::name('product_attr_level')->field('type_id,type_name')->where(['parent_id'=>0])->select()->toArray();
        return json(DefaultResponse(200, true, '获取成功', $product_attr_type));
    }



    /**
     * @desc    获取附属表信息
     * @date    2024-07-04
     * @author  luckyXiong
     */
    private function get_append_info($params=[]){
        $insert_arr =[];
        $spu            = trim($params['spu']) ?? '';
        $product_type_1 = trim($params['product_type_1']) ?? '';
        $attr_values    = $params['attr_values']??[];
        $product_attr   = Config('Logisticskey.product_attr');
        $insert_arr['spu']            = $spu;
        $insert_arr['product_type_1'] = $product_type_1;
        $insert_arr['created_time']   = date("Y-m-d H:i:s", time());
        foreach($attr_values as $v){
                $attr_parent = $product_attr[$v['parent_id']]??'';
                $attr_value  = $v['children_id']??'';
                switch($attr_parent){
                    case 'function':
                        $insert_arr['function'] = $attr_value;
                        break;
                    case 'is_steel':
                        $insert_arr['is_steel'] = $attr_value;
                        break;
                    case 'is_shoulder':
                        $insert_arr['is_shoulder']    = $attr_value;
                        break;
                    case 'adjust_shoulder':
                        $insert_arr['adjust_shoulder'] = $attr_value;
                        break;
                    case 'buckling_method':
                        $insert_arr['buckling_method'] = $attr_value;
                        break;
                    case 'chest_cushion':
                        $insert_arr['chest_cushion'] = $attr_value;
                        break;
                    case 'cup_type':
                        $insert_arr['cup_type'] = $attr_value;
                        break;
                    case 'pant_shape':
                        $insert_arr['pant_shape'] = $attr_value;
                        break;
                    case 'shap_sleeve_type':
                        $insert_arr['shap_sleeve_type'] = $attr_value;
                        break;
                    case 'shapewear_number':
                        $insert_arr['shapewear_number'] = $attr_value;
                        break;
                    case 'swim_closed_form':
                        $insert_arr['swim_closed_form'] = $attr_value;
                        break;
                    case 'panties_type':
                        $insert_arr['panties_type'] = $attr_value;
                        break;
                    case 'top_sleeve_type':
                        $insert_arr['top_sleeve_type'] = $attr_value;
                        break;
                    default:
                        break;
                }

        }
        if($attr_values){
            $insert_arr['product_attr_types'] = json_encode($attr_values);
        }
        return $insert_arr;
    }




    /**
     * @desc    获取产品扩展模块属性分类
     * @date    2024-07-11
     * @author  luckyXiong
     */
    public function get_append_level(){
        $key  = 'product_attribute_three';
        $data =  Cache::store('redis')->get($key);
        if ($data) {
            return json(DefaultResponse(200, true, "查询成功", $data));
        } else {
            $data      = Db::name('product_attr_level')->field('type_id as value,parent_id,type_name as label')->select()->toArray();
            $info_tree = listToTree($data, 'value', 'parent_id', 'children');
            //文件缓存一份;
            Cache::store('redis')->set($key,$info_tree,86400*7);
            return json(DefaultResponse(200, true, "查询成功", $info_tree ));
        }
    }


    /**
     * @desc    获取尺寸类型列表
     * @date    2024-07-04
     * @author  luckyXiong
     */
     public function getSizeLevel(){
         $size_type   = Config('Logisticskey.size_types');
         $info        = getLevel($size_type);
         foreach($info as $v){
             $arr[] = [
                 'value'      => $v['key'],
                 'label'      => $v['value'],
             ];
         }
         return  $this->jsonMessage(200,true,'获取成功!',$arr);
     }


    /**
     * @desc    获取采购类型列表  getSkuAttr
     * @date    2024-07-04
     * @author  luckyXiong
     */
    public function getPurchaseLevel(){
        $size_type   = Config('Logisticskey.purchase_types');
        $info        = getLevel($size_type);
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }


    /**
     * @desc    获取开发类型列表
     * @date    2024-10-17
     * @author  luckyXiong
     */
    public function getDevelopType(){
        $size_type   = Config('Logisticskey.develop_types');
        $info        = getLevel($size_type);
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }

    /**
     * @desc    getSkuAttr列表
     * @date    2024-07-04
     * @author  luckyXiong
     */
    public function getSkuAttr(){
        $list        = Db::name('product_options_dic')->field('id,attr_type,attr_value')->select()->toArray();
        $size_arr    = $color_arr = $old_color_arr = $new_color_arr = $letterSize = $cup_arr = $style_arr= [];
        foreach($list as $k=>$v){
                switch($v['attr_type']){
                    case 1:
                        $color_arr[$k]['id']        = $v['id'];
                        $color_arr[$k]['attr_name'] = $v['attr_value'];
                        break;
                    case 2:
                        $size_arr[$k]['id']        = $v['id'];
                        $size_arr[$k]['attr_name'] = $v['attr_value'];
                        break;
                    case 3:
                        $letterSize[$k]['id']        = $v['id'];
                        $letterSize[$k]['attr_name'] = $v['attr_value'];
                        break;
                    case 4:
                        $cup_arr[$k]['id']        = $v['id'];
                        $cup_arr[$k]['attr_name'] = $v['attr_value'];
                        break;
                    case 5:
                        $style_arr[$k]['id']        = $v['id'];
                        $style_arr[$k]['attr_name'] = $v['attr_value'];
                        break;
                }
        }

        foreach($color_arr as $v){
                if($v['id']>17){
                    $new_color_arr[] = $v;
                }else{
                    $old_color_arr[] = $v;
                }
        }

        $arr = [
            'color' =>[
                'old_color'=>$old_color_arr,
                'new_color'=>$new_color_arr,
            ],

            'sizes' =>[
                        'size'          =>array_values($size_arr),
                        'letterSize'    =>array_values($letterSize)
                      ],
            'cup'    =>array_values($cup_arr),
            'style'  =>array_values($style_arr),
        ];
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }



    /**
     * @desc    获取产品层级分类
     * @date    2024/6/29
     * @author  luckyXiong
     */
    public function getTreeList(){
        $key  = 'product_type_three';
        $data =  Cache::store('redis')->get($key);
        if ($data) {
            return json(DefaultResponse(200, true, "查询成功", $data));
        } else {
            $data      = Db::name('product_level')->field('type_id as value,parent_id,type_name as label')->select()->toArray();
            $info_tree = listToTree($data, 'value', 'parent_id', 'children');
            //文件缓存一份;
            Cache::store('redis')->set($key,$info_tree,86400*7);
            return json(DefaultResponse(200, true, "查询成功", $info_tree ));
        }
    }


    /**
     * @desc   产品数据导出
     * @author luckyXiong
     * @date   2024-07-18
     */
    public function exportInfo($params=[]){
        $list     = self::get_export_info($params);
        $product_type = $params['product_attr_id']??'1100';

        $header[] = ['产品类目', 'product_attr_type_value'];
        $header[] = ['产品spu', 'spu'];
        $header[] = ['产品名称', 'product_name'];
        $header[] = ['产品尺码范围','size_variant'];
        $header[] = ['颜色类型', 'color_variant'];
        $header[] = ['尺码类型', 'size_type'];
        $header[] = ['采购成本', 'purchase_cost'];
        $header[] = ['采购类型', 'purchase_type'];
        $header[] = ['单件物流费', 'estimate_shipping_fee'];
        $header[] = ['最大重量', 'max_weight'];
        $header[] = ['最小重量', 'min_weight'];
        $header[] = ['面料含量', 'fabric_content'];
        $header[] = ['产品状态(1:在售 2:下架)', 'product_status'];
        $header[] = ['运营者',  'develper'];
        $header[] = ['上架时间', 'published_time'];
        switch($product_type){
            case '1100': //bra类型;
                $header[] = ['功能(1:聚拢 2:运动文胸 3:哺乳文胸 4:隐形 5:无)', 'function'];
                $header[] = ['有无钢圈(1:有 2:无)', 'is_steel'];
                $header[] = ['肩带类型(1:有肩带 2:无肩带 3:可拆卸肩带)', 'is_shoulder'];
                $header[] = ['肩带是否可调(1:可调 2:不可调)', 'adjust_shoulder'];
                $header[] = ['扣带方式(1:前扣 2:后扣 3:无扣)', 'buckling_method'];
                $header[] = ['是否有胸垫(1:有 2:无)', 'chest_cushion'];
                $header[] = ['罩杯类型(1:全罩杯 2:3/4杯 3:1/2杯 4:乳贴)', 'cup_type'];
                break;

            case '1200': //shapewear类型;
                $header[] = ['裤型(1:三角型 2:短裤型 3:长裤型 4:无)', 'pant_shape'];
                $header[] = ['衣袖类型(1:长袖型 2:半袖型 3:无袖型)', 'shap_sleeve_type'];
                $header[] = ['件数(1:单件 2:2件套 3:3件套 4:4件套)', 'shapewear_number'];
                break;

            case '1300': //swim类型;
                $header[] = ['swim类型闭合形式(1:套穿 2:系带 3:卡扣)', 'swim_closed_form'];
                break;

            case '1400': //panties类型;
                $header[] = ['panties类型(1:control 2:classic 3:hipster 4:bikini 5:thong 6:boyshorts 7:period)', 'panties_type'];
                break;

            case '1500': //swim类型;
                $header[] = ['top衣袖类型(1:无袖 2:半袖 3:长袖)', 'top_sleeve_type'];
                break;
        }
        $fileName = "ProductList";
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }




    /**
     * @desc   产品数据导入消费方法
     * @author luckyXiong
     * @date   2024-07-23
     */
    public function importProductConsumer($params){
        $type = $params['type']??'';
        $spu  =  $params['B']??'';
        //数据处理公共部分;
        $operate_data = [
            'spu'                   => $spu,
            'product_attr_type'     => $type,
            'product_name'          => $params['C']??'',
            'size_variant'          => $params['D']??'',
            'color_variant'         => $params['E']??'',
            'size_type'             => $params['F']??'',
            'purchase_cost'         => $params['G']??'',
            'purchase_type'         => $params['H']??'',
            'estimate_shipping_fee' => $params['I']??'',
            'max_weight'            => $params['J']??'',
            'min_weight'            => $params['K']??'',
            'fabric_content'        => $params['L']??'',
            'product_status'        => $params['M']??'',
            'develper'              => $params['N']??'',
            'published_time'        => $params['O']??'',
            'source_link'           => $params['P']??'',
        ];

        //数据处理公共部分;
        $append_data = [
               'spu'              =>$spu,
               'product_attr_type'=>$type,
        ];
        $product_attr_types = [];
        switch($type){
               case "1100": //bra类型数据
                   $append_data['function']           = $params['Q']??'';
                   $append_data['is_steel']           = $params['R']??'';
                   $append_data['is_shoulder']        = $params['S']??'';
                   $append_data['adjust_shoulder']    = $params['T']??'';
                   $append_data['buckling_method']    = $params['U']??'';
                   $append_data['chest_cushion']      = $params['V']??'';
                   $append_data['cup_type']           = $params['W']??'';
                   if($append_data['function']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['function'],
                           'parent_id'  =>'1101',
                       ];
                   }
                   if($append_data['is_steel']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['is_steel'],
                           'parent_id'=>'1102',
                       ];
                   }

                   if($append_data['is_shoulder']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['is_shoulder'],
                           'parent_id'=>'1103',
                       ];
                   }

                   if($append_data['adjust_shoulder']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['adjust_shoulder'],
                           'parent_id'=>'1104',
                       ];
                   }

                   if($append_data['buckling_method']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['buckling_method'],
                           'parent_id'=>'1105',
                       ];
                   }


                   if($append_data['chest_cushion']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['chest_cushion'],
                           'parent_id'=>'1106',
                       ];
                   }

                   if($append_data['cup_type']){
                       $product_attr_types[] = [
                           'children_id'  =>$append_data['cup_type'],
                           'parent_id'=>'1107',
                       ];
                   }
               break;

            case "1200": //shapewear类型
                $append_data['pant_shape']           = $params['Q']??'';
                $append_data['shap_sleeve_type']     = $params['R']??'';
                $append_data['shapewear_number']     = $params['S']??'';
                if($append_data['pant_shape']){
                    $product_attr_types[] = [
                        'children_id'  =>$append_data['pant_shape'],
                        'parent_id'    =>'1201',
                    ];
                }

                if($append_data['shap_sleeve_type']){
                    $product_attr_types[] = [
                        'children_id'  =>$append_data['shap_sleeve_type'],
                        'parent_id'    =>'1202',
                    ];
                }

                if($append_data['shapewear_number']){
                    $product_attr_types[] = [
                        'children_id'  =>$append_data['shapewear_number'],
                        'parent_id'    =>'1203',
                    ];
                }
                break;

            case "1300": //swim类型
                $append_data['swim_closed_form']     = $params['Q']??'';
                if($append_data['swim_closed_form']){
                    $product_attr_types[] = [
                        'children_id'  =>$append_data['swim_closed_form'],
                        'parent_id'    =>'1301',
                    ];
                }
                break;

            case "1400": //panties类型
                $append_data['panties_type']         = $params['Q']??'';
                $panties_type                        = explode(',',$append_data['panties_type']);
                if($panties_type){
                    foreach($panties_type as $v){
                          $temp = [
                              'children_id'=> $v,
                              'parent_id'  => '1401',
                          ];
                        $product_attr_types[] = $temp;
                    }
                }
                break;

            case "1500": //top类型
                $append_data['top_sleeve_type']      = $params['Q']??'';
                if($append_data['top_sleeve_type']){
                    $product_attr_types[] = [
                        'children_id'  =>$append_data['top_sleeve_type'],
                        'parent_id'    =>'1501',
                    ];
                }
                break;
           }

           if($product_attr_types){
               $append_data['product_attr_types'] = json_encode($product_attr_types);
           }

           //查看当前记录是否存在;
           $exist_info = Db::name('product')->field('id,spu,product_name')->where(['spu'=>$spu])->find();
           if($exist_info){

                //记录日志
                $insert = [
                    'admin_id'=>$params['adminId'] ?? 0,
                    'url'=>'/product/product/import',
                    'method'=>'post',
                    'title'=>'产品',
                    'content'=>"导入修改产品",
                    'ip'=>$_SERVER['REMOTE_ADDR'],
                    'useragent'=>$_SERVER['HTTP_USER_AGENT'],
                    'create_time'=>date("Y-m-d H:i:s", time()),
                    'json'=> json_encode($operate_data,true),
                ];
                Db::name('system_log')->insert($insert);
                //记录日志结束

               Db::name('product')->where('id',$exist_info['id'])->update($operate_data);
               $exist_oppend = Db::name('product_append')->where(['spu'=>$spu])->find();
               if($exist_oppend){
                   Db::name('product_append')->where('id',$exist_oppend['id'])->update($append_data);
               }else{
                   $append_data['created_time'] = date("Y-m-d H:i:s", time());
                   Db::name('product_append')->insert($append_data);
               }
           }else{
               $product_id = Db::name('product')->insertGetId($operate_data);
               $append_data['product_id'] = $product_id;
               $append_data['created_time'] = date("Y-m-d H:i:s", time());
               Db::name('product_append')->insert($append_data);
           }
           return  true;
    }



    /**
     * @desc   产品数据导入
     * @author luckyXiong
     * @date   2024-07-18
     */
    public function get_export_info($params=[]){
        $spu             = getIsset($params,'spu');
        $product_attr_id = getIsset($params,'product_attr_id');
        $published_time  = getIsset($params,'published_time');
        $purchase_type   = getIsset($params,'purchase_type');
        $develop_type    = getIsset($params,'develop_type');
        $where = [];

        if($spu){
            $where[] = ['p.spu', 'like', '%' . $spu . '%'];
        }

        if (!empty($published_time)) {
            $where[]  = ['p.created_time', '>=', date('Y-m-d H:i:s',strtotime($published_time[0]))];
            $where[]  = ['p.created_time', '<=', date('Y-m-d H:i:s',strtotime($published_time[1]) + 3600*24-1)];
        }

        if($purchase_type){
            $where[] = ['p.purchase_type', '=',$purchase_type];
        }

        if($develop_type){
            $where[] = ['p.develop_type', '=',$develop_type];
        }

        if($product_attr_id){
            $where[] = ['p.product_attr_type', '=',$product_attr_id];
        }

        $order = ['p.created_time DESC'];

        $field = 'p.id,p.spu,p.product_type_1,p.product_type_2,p.product_name,p.size_variant,p.color_variant,p.product_size_images,p.size_type,
                  p.purchase_cost,p.month_purchase_cost,p.source_link,p.max_weight,p.min_weight,p.estimate_shipping_fee,
                  p.published_time,p.product_status,p.develper,p.remarks,p.product_images,p.source_link,p.remarks,p.fabric_content,append.is_steel,append.is_shoulder,append.adjust_shoulder,append.buckling_method,
                  append.cup_type,append.pant_shape,p.product_attr_type,p.purchase_type,append.shap_sleeve_type,append.shapewear_number,append.swim_closed_form,append.panties_type,append.top_sleeve_type,
                  append.function,append.chest_cushion';

        $list   = Db::name('product')
            ->alias('p')
            ->leftJoin('product_append append', 'p.spu = append.spu')
            ->field($field)
            ->where($where)
            ->order($order)
            ->select();
        $list = objectToArray($list);

        //批量获取产品大类;
        $product_types      = array_column($list,'product_type_1');
        $product_types_info = Db::name('product_level')->field('type_id,type_name')->whereIn('type_id',$product_types)->select();
        $product_types_info = objectToArray($product_types_info);
        $product_types_map  = array_column($product_types_info,null,'type_id');

        $product_attr_type = Db::name('product_attr_level')->field('type_id,type_name')->where(['parent_id'=>0])->select()->toArray();
        $product_attr_type_map = array_column($product_attr_type,null,'type_id');

        foreach($list as $k=>$v){
            $product_type                        = $product_types_map[$v['product_type_1']]??[];
            $list[$k]['product_type_1']          = $product_type['type_name']??'';
            $product_attr_type_value             = $product_attr_type_map[$v['product_attr_type']]??[];
            $list[$k]['product_attr_type_value'] = $product_attr_type_value['type_name']??'';
        }
        return  $list;
    }



    /**
     * @desc     查询运营角色
     * @author   luckyXiong
     * @date     2025-07-25
     */
    public function getSoleType($params=[]){
        $groupId    = $params['group_id'] ?? "";
        if($groupId ==11){
             return  1;
        }else{
              return 2;
        }
    }




    /**
     * @desc   产品数据导入
     * @author luckyXiong
     * @date   2024-06-24
     */
    public function importInfo($url='',$type=''){
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelData        = isset($data[0]) ? $data[0] : $data;
        if(!$excelData)    return json(DefaultResponse(201, false, '暂无数据!', null));
        foreach ($excelData as $value) {
            $filteredArray     = array_filter($value);
            if($filteredArray){
                //数据推送到队列;
                $value['type'] = $type;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_PRODUCT_IMPORT_QUEUE,
                    $value,
                    false
                );
            }
        }
    }




    /**
     * @desc   获取尺码类型
     * @author luckyXiong
     * @date   2024-06-27
     */
    public function get_size_type($size_type=''){
        if(!$size_type) return  0;
        $size_type  = explode(',',$size_type);
        $arr        = Config('Logisticskey.size_type');
        $info       = [];
        foreach($size_type as  $v){
            $info[] = $arr[$v];
        }
        return  implode(',',$info);
    }


    /**
     * @desc   获取货源链接
     * @author luckyXiong
     * @date   2024-06-27
     */
    public function get_supply_link($supply_link=''){
        if(!$supply_link) return  '';
        $supply_link  = explode(',',$supply_link);
        return   json_encode($supply_link,JSON_UNESCAPED_UNICODE);
    }


    /**
     * @desc   获取属性值
     * @author luckyXiongColor
     * @date   2024-07-07
     */
    public function get_attr(){
        $list = Db::name('product_options_api')->where(['name'=>'Size'])->select()->toArray();
        $arr  = $info = $insert = [];
        foreach ($list as $k=>$v){
            $v['values'] = json_decode($v['values'],true);
            foreach($v['values'] as $value){
                $arr = [
                    'attr_type' =>2,
                    'attr_value'=>$value,
                ];
                $info[] = $arr;
            }
        }

        $unique_ids = array_unique(array_column($info, 'attr_value'));

        // 过滤原始数组，只保留唯一字段值的项
        $filtered_array = array_filter($info, function ($item) use ($unique_ids) {
            static $found = [];
            if (in_array($item['attr_value'], $found)) {
                return false; // 已经找到的ID，跳过
            } else {
                $found[] = $item['attr_value']; // 记录新找到的ID
                return true;
            }
        });

        $arr_info = array_values($filtered_array);

        foreach($arr_info as $item){

            $temp = [
                'attr_type' =>$item['attr_type'],
                'attr_value'=>$item['attr_value'],
            ];
            $insert[] = $temp;
        }

        p($insert);die;

    }


    /**
     * @desc    产品数据导入消费方法
     * @author  luckyXiong
     * @date    2024-07-23
     */
    public function productImportConsumer(){






    }








}